<?php
/*
+--------------------------------------------------------------------------
|   Anwsion [#RELEASE_VERSION#]
|   ========================================
|   by Tatfook Network Team
|   (c) 2011 - 2012 Anwsion Software
|   http://www.anwsion.com
|   ========================================
|   Support: zhengqiang@gmail.com
|   
+---------------------------------------------------------------------------
*/

class index_class extends AWS_MODEL
{
	const CATEGORY_INDEX_PEOPLE = 1; //我关注的人（他关注的人，他关注的话题）
	const CATEGORY_INDEX_TOPIC = 2; //我关注的话题（谁关注了相同的话题）
	const CATEGORY_INDEX_QUESTION = 3; //我回复过的问题（包含我没关注的话题）

	
	/**
	 * 获取首页我关注的模块内容 V2
	 *
	 * @param  $uid
	 * @param  $limit
	 */
	function get_index_focus($uid, $limit = 10, $get_type = 'all')
	{
		$index_actions_day_limit = intval(get_setting('index_actions_day_limit'));
		
		if ($index_actions_day_limit <= 0)
		{
			$index_actions_day_limit = 30;
		}
		
		$add_time = time() - 60 * 60 * 24 * $index_actions_day_limit;
		
		$my_focus_question_array[0] = 0; // 我关注的问题
		$my_focus_topics_questions_array[0] = 0; // 我关注的话题的问题
		$question_action_array[0] = 0; // 我关注的问题和关注话题的问题的集合
		$my_focus_topics_id_array[0] = 0; // 我关注的话题集合
		$my_follow_uids_array[0] = 0;
		$my_focus_topics_by_questions = array(); //	我关注的话题 BY 问题 ID
		

		$answer_all_ids = array();
		
		$questions_uninteresteds = $this->model('question')->get_question_uninterested($uid);
		
		if (! $questions_uninteresteds)
		{
			$questions_uninteresteds[0] = 0;
		}
		
		//我关注的问题
		if ($my_focus_question_list_all = $this->model('question')->get_focus_question_list_by_uid(false, $uid, false))
		{
			foreach ($my_focus_question_list_all as $key => $val)
			{
				if (! isset($question_action_array[$val['question_id']]))
				{
					$question_action_array[$val['question_id']] = $val['question_id']; //存我关注的话题的问题集合				
					$my_focus_question_array[] = $val['question_id'];
				}
			}
		}
		
		//pd($my_focus_question_array);
		

		//我关注的话题
		$my_focus_topics = $this->model('topic')->get_focus_topic_list(false, $uid, false);
		
		if ($my_focus_topics)
		{
			foreach ($my_focus_topics as $key => $val)
			{
				if (empty($val['topic_id']))
				{
					continue;
				}
				
				$my_focus_topics_id_array[] = $val['topic_id'];
			}
			
			$my_focus_topics_id_array = array_unique($my_focus_topics_id_array);
			
			if ($my_focus_topics_questions = $this->model('question_topic')->get_question_list_by_topic_id($my_focus_topics_id_array, false))
			{
				foreach ($my_focus_topics_questions as $key => $val)
				{
					if (! isset($question_action_array[$val['question_id']]))
					{
						$question_action_array[$val['question_id']] = $val['question_id'];
						$my_focus_topics_questions_array[] = $val['question_id']; // 存我关注的话题的问题集合
						$my_focus_topics_by_questions[$val['question_id']] = array(
							'topic_id' => $val['topic_id'], 
							'topic_title' => $val['topic_title']
						); // 存我关注的话题 BY 问题 ID
					}
				}
			}
		}
		
		//我关注的人
		if ($my_follow_uids = $this->model('follow')->get_user_friends($uid, false))
		{
			foreach ($my_follow_uids as $key => $val)
			{
				$my_follow_uids_array[] = $val['uid'];
			}
		}
		
		//return false;
		

		$action_ids0 = "201, 401"; // 回复问题, 创建问题
		$action_ids0b = "101"; // 添加问题
		$action_ids1a = "201"; // 回复问题
		$action_ids1b = "401"; // 创建话题
		$action_ids2 = "101, 201, 204, 401"; // 添加问题, 回复问题, 增加赞同, 创建话题
		$action_ids3 = "105"; // 添加问题关注
		

		//我关注的问题
		//我关注的话题的回复
		//我关注的话题添加的问题
		//我关注的人添加问题, 回复问题, 赞成回答, 增加话题
		//我关注的人关注了问题
		

		$where = "(
			(associate_type = " . ACTION_LOG::CATEGORY_QUESTION . "
			AND associate_id IN (" . implode(',', $my_focus_question_array) . ")
			AND associate_action IN({$action_ids0}) AND uid <> " . $uid . ")
				
			OR 			
			(associate_type = " . ACTION_LOG::CATEGORY_QUESTION . "
			AND associate_id IN (" . implode(',', $my_focus_question_array) . ")
			AND associate_action IN({$action_ids0b}) AND uid = " . $uid . ")				
				
			OR
			(associate_type = " . ACTION_LOG::CATEGORY_QUESTION . "
			AND associate_id IN (" . implode(',', $my_focus_topics_questions_array) . ")
			AND associate_action IN({$action_ids1a}) AND uid <> " . $uid . ")
				
			OR
			(associate_type = " . ACTION_LOG::CATEGORY_QUESTION . "
			AND associate_id IN (" . implode(',', $my_focus_topics_questions_array) . ")
			AND associate_attached IN (" . implode(',', $my_focus_topics_id_array) . ")
			AND associate_action IN({$action_ids1b}) )
		
			OR
			(associate_type = " . ACTION_LOG::CATEGORY_QUESTION . "
			AND uid IN (" . implode(',', $my_follow_uids_array) . ")
			AND associate_action IN({$action_ids2}))
		
			OR
			(associate_type = " . ACTION_LOG::CATEGORY_QUESTION . "
			AND uid IN (" . implode(',', $my_follow_uids_array) . ")
			AND associate_action IN ({$action_ids3}) AND associate_id NOT IN (" . implode(',', $my_focus_question_array) . "))
		
			)
			AND
			(associate_type = " . ACTION_LOG::CATEGORY_QUESTION . "
			AND associate_id NOT IN (" . implode(',', $questions_uninteresteds) . ")
		)";
		
		$action_list = ACTION_LOG::get_actions_distint_by_where($where, $limit, $add_time);
		
		$tmp_all_question_array[0] = 0;
		$tmp_all_answer_array[0] = 0;
		$tmp_all_topic_info_array[0] = 0;
		$tmp_all_user_id_array[0] = 0;
		
		foreach ($action_list as $key => $val)
		{
			$tmp_all_question_array[] = $val['associate_id'];
			
			if (in_array($val['associate_action'], array(
				201, 
				204
			)))
			{
				$tmp_all_answer_array[] = $val['associate_attached'];
			}
			
			if (in_array($val['associate_action'], array(
				401
			)))
			{
				$tmp_all_topic_info_array[] = $val['associate_attached'];
			}
			
			if (! in_array($val['uid'], $tmp_all_user_id_array))
			{
				$tmp_all_user_id_array[] = $val['uid'];
			}
		
		}
		
		$question_infos_rs = $this->model('question')->get_question_info_by_ids($tmp_all_question_array);
		
		foreach ($question_infos_rs as $key => $val)
		{
			$question_infos[$val['question_id']] = $val;
		}
		
		$answer_infos_rs = $this->fetch_all('answer', 'answer_id IN (' . implode(',', $tmp_all_answer_array) . ')');
		
		foreach ($answer_infos_rs as $key => $val)
		{
			$answer_infos[$val['answer_id']] = $val;
		}
		
		$topic_infos_rs = $this->fetch_all('topic', 'topic_id IN(' . implode(',', $tmp_all_topic_info_array) . ')');
		
		foreach ($topic_infos_rs as $key => $val)
		{
			$topic_infos[$val['topic_id']] = $val;
		}
		
		if ($tmp_all_user_id_array)
		{
			if ($user_info_list_rs = $this->model('account')->get_users_by_uids($tmp_all_user_id_array, true))
			{
				
				foreach ($user_info_list_rs as $key => $val)
				{
					$user_info_more_list[$val['uid']] = $val;
					$user_info_list[$val['uid']] = $val['user_name'];
				}
			}
		
		}
		
		//重组信息		
		foreach ($action_list as $key => $val)
		{
			$topic_info = null;
			$answer_list = null;
			
			if (! isset($user_info_list[$val['uid']]))
			{
				$user_info_more_list[$val['uid']] = $this->model('account')->get_users_by_uid($val['uid'], true);
				$user_info_list[$val['uid']] = $user_info_more_list[$val['uid']]['user_name'];
			}
			
			$action_list[$key]['user_info'] = $user_info_more_list[$val['uid']];
			
			if (in_array($val['associate_action'], array(
				401
			)))
			{
				/*if (count($val['all_topics']) > 1)
				{
					$topic_info = $this->model('topic')->get_topics($val['all_topics']);
				}
				else
				{*/
				$topic_info = $topic_infos[$val['associate_attached']];
				//}
			}
			
			if (isset($my_focus_topics_by_questions[$val['associate_id']]))
			{
				if (! $topic_info)
				{
					$topic_info = $my_focus_topics_by_questions[$val['associate_id']];
				}
			}
			
			$question_info = $question_infos[$val['associate_id']];
			
			//是否关注
			if (in_array($question_info['question_id'], $my_focus_question_array))
			{
				$question_info['has_focus'] = true;
			}
			else
			{
				$question_info['has_focus'] = false;
			}
			
			//我关注的问题,要排除发起的动作			
			if ((in_array($val['associate_id'], $my_focus_question_array) && (! in_array($val['associate_action'], array(
				101, 
				204
			)))))
			{
				$question_info['last_action_str'] = "<span style='display:none'>P0*" . $val['history_id'] . "</span>" . ACTION_LOG::format_action_str_V2($val['associate_action'], $val['uid'], null, null, $topic_info, 2, $question_info['answer_count']);
			}
			else if (in_array($val['uid'], $my_follow_uids_array)) //我关注的人
			{
				$question_info['last_action_str'] = "<span style='display:none'>P1*" . $val['history_id'] . "</span>" . ACTION_LOG::format_action_str_V2($val['associate_action'], $val['uid'], $user_info_list[$val['uid']], null, $topic_info, 3, $question_info['answer_count']);
			}
			else if (in_array($val['uid'], array(
				$uid
			))) //我自己的动作
			{
				$question_info['last_action_str'] = "<span style='display:none'>P1*" . $val['history_id'] . "</span>" . ACTION_LOG::format_action_str_V2($val['associate_action'], $val['uid'], $user_info_list[$val['uid']], null, null, 3, $question_info['answer_count']);
			}
			else
			{
				$question_info['last_action_str'] = "<span style='display:none'>P2*" . $val['history_id'] . "</span>" . ACTION_LOG::format_action_str_V2($val['associate_action'], $val['uid'], null, null, $topic_info, 2, $question_info['answer_count']);
			}
			//pd($question_info['last_action_str']);
			

			//对于回复问题的
			if (($question_info['answer_count'] > 0) && (in_array($val['associate_action'], array(
				201, 
				204
			))))
			{
				//取里面的回复的ID出来
				$answer_list[0] = $answer_infos[$val['associate_attached']];
				//补充数据
				

				if (! isset($user_info_list[$answer_list[0]['uid']]))
				{
					$user_info_more_list[$answer_list[0]['uid']] = $this->model('account')->get_users_by_uid($answer_list[0]['uid'], true);
					$user_info_list[$answer_list[0]['uid']] = $user_info_more_list[$answer_list[0]['uid']]['user_name'];
				}
				
				$answer_list[0]['uid'] = $user_info_more_list[$answer_list[0]['uid']]['uid'];
				$answer_list[0]['uname'] = $user_info_more_list[$answer_list[0]['uid']]['user_name'];
				$answer_list[0]['avatar_file'] = $user_info_more_list[$answer_list[0]['uid']]['avatar_file'];
				$answer_list[0]['signature'] = $user_info_more_list[$answer_list[0]['uid']]['signature'];
			
			}
			
			//处理回复
			if (! empty($answer_list[0]['answer_id']))
			{
				$answer_all_ids[] = $answer_list[0]['answer_id'];
				
				
				$answer_list_content = FORMAT::format_content(strip_ubb($answer_list[0]['answer_content']));
				$answer_list[0]['answer_content'] = $answer_list_content['content_content'];
				$answer_list[0]['answer_title'] = $answer_list_content['content_title'];
					
				if ($answer_list[0]['has_attach'])
				{
					$answer_list[0]['attachs'] = $this->model('publish')->get_attach('answer', $answer_list[0]['answer_id'], 'min');
				}
				
				$question_info['answer_info'] = $answer_list[0];
			}
			
			//还原到单个数组 ROW 里面
			foreach ($question_info as $qkey => $qval)
			{
				if ($qkey == 'add_time')
				{
					continue;
				}
				
				$action_list[$key][$qkey] = $qval;
			}
		
		}
		
		if ($answer_all_ids)
		{
			$answer_agree_users = $this->model('answer')->get_vote_user_by_answer_ids($answer_all_ids);
			$answer_vote_status = $this->model('answer')->get_answer_vote_status($answer_all_ids, $uid);
		}
		
		foreach ($action_list as $key => $val)
		{
			if (isset($action_list[$key]['answer_info']['answer_id']))
			{
				$answer_id = $action_list[$key]['answer_info']['answer_id'];
				
				if (isset($answer_agree_users[$answer_id]))
				{
					$action_list[$key]['answer_info']['agree_users'] = $answer_agree_users[$answer_id];
				}
				
				if (isset($answer_vote_status[$answer_id]))
				{
					$action_list[$key]['answer_info']['agree_status'] = intval($answer_vote_status[$answer_id]['vote_value']);
				}
			}
		}
		
		return $action_list;
	}

	/**
	 * 获取用户关注的内容
	 * @param  $uid
	 * @param  $limit
	 */
	public function get_user_focus($uid, $limit = 10)
	{
		$associate = $this->fetch_all("user_associate_index", " uid = " . (int)$uid . " AND (associate_type = 1 OR associate_type = 2)", " update_time DESC ", $limit);
		$question_ids = array(
			0
		);
		
		if ($associate)
		{
			foreach ($associate as $key => $val)
			{
				if ($val['associate_type'] == 1)
				{
					$question_ids[] = $val['associate_id'];
				}
				else
				{
					$competitions_ids[] = $val['associate_id'];
				}
			}
		}
		
		if ($_question = $this->fetch_all('question', "question_id IN(" . implode($question_ids, ',') . ")"))
		{
			foreach ($_question as $key => $val)
			{
				$question[$val['question_id']] = $val;
			}
		}
		
		if ($associate)
		{
			foreach ($associate as $key => $val)
			{
				if ($val['associate_type'] == 1)
				{
					$result[] = $question[$val['associate_id']];
				}
			
			}
		}
		return $result;
	}

	/**
	 * 获取用户发布的内容
	 * @param  $uid
	 * @param  $limit
	 */
	public function get_user_publish($uid, $limit = 10)
	{
		$associate = $this->fetch_all("user_associate_index", " uid = " . (int)$uid . " AND (associate_type = 3 OR associate_type = 4)", "update_time DESC", $limit);
		
		$question_ids = array(
			0
		);
		
		$competitions_ids = array(
			0
		);
		
		if ($associate)
		{
			foreach ($associate as $key => $val)
			{
				if ($val['associate_type'] == 3)
				{
					$question_ids[] = $val['associate_id'];
				}
				else
				{
					$competitions_ids[] = $val['associate_id'];
				}
			}
		}
		
		$_question = $this->fetch_all('question', "question_id IN(" . implode($question_ids, ',') . ")");
		
		if ($_question)
		{
			foreach ($_question as $key => $val)
			{
				$question[$val['question_id']] = $val;
			}
			
			foreach ($associate as $key => $val)
			{
				if ($val['associate_type'] == 3)
				{
					$result[] = $question[$val['associate_id']];
				}
			}
		}
		return $result;
	}

	/**
	 * 获取热门用户
	 * @param  $uid
	 * @param  $category
	 * @param  $limit
	 */
	public function get_hot_users($uid = 0, $category = 0, $limit = 10)
	{
		
		$uid = intval($uid);
		$category = intval($category);
		$cache_key = "hot_user_" . $category . '_' . $limit;
		
		$data = $this->model('db_cache')->load($cache_key);
		
		if (! $data)
		{
			$hot_user_period = get_setting('hot_user_period');
			
			if (! $hot_user_period)
			{
				$hot_user_period = 30;
			}
			
			$min_time = time() - 60 * 60 * 24 * $hot_user_period;
			
			if ($category > 0)
			{
				$sql = "SELECT uid FROM " . $this->get_table("answer") . " WHERE category_id = " . $category . " AND add_time > " . $min_time;
			}
			else
			{
				$sql = "SELECT uid FROM  " . $this->get_table("answer") . " WHERE add_time > " . $min_time;
			}
			
			if ($answer_rs = $this->query_all($sql))
			{
				foreach ($answer_rs as $key => $val)
				{
					if (! $user_answer_count[$val['uid']])
					{
						$user_answer_count[$val['uid']] = 1;
					}
					else
					{
						$user_answer_count[$val['uid']] ++;
					}
				}
			}
			
			if ($category > 0)
			{
				$user_answer_all_count = $this->count("answer", " category_id='" . $category . "' AND add_time > " . $min_time);
				
				$sql = "SELECT  answer_uid FROM  " . $this->get_table("answer_vote") . " WHERE answer_id IN (SELECT answer_id FROM " . $this->get_table("answer") . " WHERE category_id = " . $category . " AND add_time > " . $min_time . " ) AND vote_value = 1";
			}
			else
			{
				$user_answer_all_count = $this->count("answer", "add_time > " . $min_time);
				
				$sql = " SELECT answer_uid FROM  " . $this->get_table("answer_vote") . " WHERE answer_id IN (SELECT answer_id FROM " . $this->get_table("answer") . "  WHERE add_time > " . $min_time . " )  AND vote_value = 1";
			}
			
			if ($vote_rs = $this->query_all($sql))
			{
				foreach ($vote_rs as $key => $val)
				{
					if (! $user_vote_count[$val['answer_uid']])
					{
						$user_vote_count[$val['answer_uid']] = 1;
					}
					else
					{
						$user_vote_count[$val['answer_uid']] ++;
					}
				}
			}
			
			//取出所有用户
			$users_list = $this->model("account")->get_users_list('', null, true, false);
			
			//计算数组得分
			if ($users_list)
			{
				foreach ($users_list as $key => $val)
				{
					
					$user_answer_count[$val['uid']] = intval($user_answer_count[$val['uid']]);
					$user_vote_count[$val['uid']] = intval($user_vote_count[$val['uid']]);
					$scores = 0;
					
					if ($user_answer_count[$val['uid']])
					{
						$scores = $user_answer_count[$val['uid']] + $user_vote_count[$val['uid']];
					}
					
					//$scores = $scores + $val['online_time'] / 60 * 60 * 24 * get_setting('hot_user_period');
					$a_user_list[$val['uid']] = array(
						"users" => $val, 
						"scores" => $scores
					);
				
				}
			}
			
			if (is_array($a_user_list))
			{
				$a_user_list = aasort($a_user_list, array(
					"-scores"
				));
			}
			
			//ZCACHE::set($cache_key, $a_user_list, null, get_setting('cache_level_high'));
			

			//数组排序
			if ($a_user_list)
			{
				
				foreach ($a_user_list as $key => $val)
				{
					
					// 						if ($user_answer_count[$val['users']['uid']]*1<1)
					// 						{
					// 							continue;
					// 						}
					// 						else
					// 						{
					

					$hot_user_list[] = array(
						'uid' => $val['users']['uid'], 
						'scores' => $val['scores']
					);
					// 						}
				}
			
			}
			
			//ZCACHE::set($cache_key, $a_user_list, null, get_setting('cache_level_high'));
			

			if ($limit && $hot_user_list)
			{
				$limit_tmp = preg_split("/,/", $limit);
				
				if (count($limit_tmp) == 2)
				{
					$offset = intval($limit_tmp[0]);
					$length = intval($limit_tmp[1]);
					
					$hot_user_list = array_slice($hot_user_list, $offset, $length);
				
				}
				else if (count($limit_tmp) == 1)
				{
					$length = intval($limit_tmp[0]);
					$hot_user_list = array_slice($hot_user_list, 0, $length);
				}
				
				$this->model('db_cache')->save($cache_key, $hot_user_list, 60);
				return $hot_user_list;
			}
		
		}
		else
		{
			return $data;
		
		}
	
	}

	/**
	 * 获取热门用户V2
	 * @param  $uid
	 * @param  $category
	 * @param  $limit
	 */
	public function get_hot_users_V2($uid = 0, $category = 0, $limit = 10)
	{
		$uid = intval($uid);
		$category = intval($category);
		$cache_key = "hot_user_" . $category . '_' . $limit;
		
		$data = $this->model('db_cache')->load($cache_key);
		
		if (! $data)
		{
			if ($category > 0)
			{
				
				$sql = "SELECT MEM.uid 
						FROM " . $this->get_table('users') . " MEM 
						LEFT JOIN " . $this->get_table('reputation_category') . "  AS RC ON MEM.uid=RC.uid
						WHERE (MEM.group_id <> 3 AND MEM.forbidden = 0)
						AND  (RC.category_id=" . $category . " OR  ISNULL( RC.category_id))
						ORDER BY RC.reputation DESC ,MEM.reputation DESC ";
				
				$rs = $this->query_all($sql, $limit);
			
			}
			else
			{
				//取出所有用户
				$rs = $this->model("account")->get_users_list('', $limit, true, false, ' reputation DESC');
			}
			
			if ($rs)
			{
				foreach ($rs as $key => $val)
				{
					
					$hot_user_list[] = array(
						'uid' => $val['uid']
					);
				}
			
			}
			
			$this->model('db_cache')->save($cache_key, $hot_user_list, 60);
			
			return $hot_user_list;
		}
		else
		{
			return $data;
		}
	
	}
}